#!/bin/bash

# CActor 项目环境配置脚本
# 用于配置仓颉语言0.60.5开发环境

echo "🚀 配置CActor项目环境..."

# 检查操作系统
if [[ "$OSTYPE" == "darwin"* ]]; then
    echo "✅ 检测到macOS系统"
    
    # 设置macOS系统库路径
    export AARCH64_MACOS_LIBS="/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
    export AARCH64_MACOS_MACRO_LIBS="/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
    
    echo "✅ 已设置macOS系统库环境变量"
    echo "   AARCH64_MACOS_LIBS=$AARCH64_MACOS_LIBS"
    echo "   AARCH64_MACOS_MACRO_LIBS=$AARCH64_MACOS_MACRO_LIBS"
    
    # 检查并添加到shell配置文件
    SHELL_CONFIG=""
    if [[ "$SHELL" == *"zsh"* ]]; then
        SHELL_CONFIG="$HOME/.zshrc"
    elif [[ "$SHELL" == *"bash"* ]]; then
        SHELL_CONFIG="$HOME/.bash_profile"
    fi
    
    if [[ -n "$SHELL_CONFIG" ]]; then
        # 检查是否已经配置
        if ! grep -q "AARCH64_MACOS_LIBS" "$SHELL_CONFIG" 2>/dev/null; then
            echo "" >> "$SHELL_CONFIG"
            echo "# CActor 仓颉语言环境配置" >> "$SHELL_CONFIG"
            echo "export AARCH64_MACOS_LIBS=\"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib\"" >> "$SHELL_CONFIG"
            echo "export AARCH64_MACOS_MACRO_LIBS=\"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib\"" >> "$SHELL_CONFIG"
            echo "✅ 已添加环境变量到 $SHELL_CONFIG"
        else
            echo "✅ 环境变量已存在于 $SHELL_CONFIG"
        fi
    fi
    
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    echo "✅ 检测到Linux系统"
    # Linux环境配置（如需要）
    echo "ℹ️  Linux环境暂不需要特殊配置"
else
    echo "⚠️  未识别的操作系统: $OSTYPE"
fi

# 验证仓颉语言工具链
echo ""
echo "🔍 验证仓颉语言工具链..."

if command -v cjpm &> /dev/null; then
    echo "✅ cjpm 已安装"
    cjpm --version
else
    echo "❌ cjpm 未找到，请确保仓颉语言工具链已正确安装"
    exit 1
fi

# 验证系统库
echo ""
echo "🔍 验证系统库..."
if [[ "$OSTYPE" == "darwin"* ]]; then
    if [[ -f "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd" ]]; then
        echo "✅ macOS系统库已找到"
    else
        echo "❌ macOS系统库未找到，请安装Xcode Command Line Tools:"
        echo "   xcode-select --install"
        exit 1
    fi
fi

echo ""
echo "🎉 环境配置完成！"
echo ""
echo "📋 下一步操作："
echo "1. 重新加载shell配置: source ~/.zshrc (或 source ~/.bash_profile)"
echo "2. 构建项目: cjpm build"
echo "3. 运行测试: cjpm test"
echo ""
echo "💡 提示: 如果遇到问题，请检查环境变量是否正确设置"
